using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace Admin2025.Infrastructure.Data
{
    /// <summary>
    /// 设计时 DbContext 工厂，用于 EF Core 迁移等命令行操作。
    /// </summary>
    public class AdminDbContextFactory : IDesignTimeDbContextFactory<AdminDbContext>
    {
        /// <summary>
        /// 创建 AdminDbContext 实例，供 EF Core 设计时工具使用。
        /// </summary>
        /// <param name="args">命令行参数。</param>
        /// <returns>AdminDbContext 实例。</returns>
        public AdminDbContext CreateDbContext(string[] args)
        {
            // 获取基础路径，指向 API 项目目录
            var basePath = Path.Combine(Directory.GetCurrentDirectory(), "..", "Admin2025.Api");
            // 构建配置，加载 appsettings.Development.json 和 appsettings.json
            var configuration = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appsettings.Development.json", optional: true)
                .AddJsonFile("appsettings.json", optional: true)
                .Build();

            // 获取 MySql 连接字符串
            var connectionString = configuration.GetConnectionString("MySql");
            if (string.IsNullOrWhiteSpace(connectionString))
                throw new InvalidOperationException("未找到 MySql 的连接字符串。");

            // 配置 DbContext 选项，使用 MySql 数据库
            var optionsBuilder = new DbContextOptionsBuilder<AdminDbContext>();
            optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));

            // 返回 AdminDbContext 实例
            return new AdminDbContext(optionsBuilder.Options);
        }
    }
}